//
//  B_addJLGJViewController.m
//  Estate
//
//  Created by heyong on 16/6/21.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#define LINE_Y 20

#import "B_addJLGJViewController.h"

#import "UIActionSheet+Common.h"
#import "PictureViewController.h"


#import "AttachmentPhotoCell.h"

@interface B_addJLGJViewController ()<UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong)UITableView  *tableView;

@property (strong, nonatomic) Tweet *curTweet;

// 记录通知传过来的数据
@property (strong, nonatomic) NSDictionary *centerDic;

@end


@implementation B_addJLGJViewController

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, DEF_SCREEN_WIDTH / 2 , DEF_SCREEN_HEIGHT-154) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.bounces=NO;
        _tableView.showsVerticalScrollIndicator=NO;
        _tableView.separatorStyle = NO;
        _tableView.backgroundColor = [UIColor whiteColor];
        
        [_tableView registerClass:[AttachmentPhotoCell class] forCellReuseIdentifier:@"cell1"];
    }
    return _tableView;
}

- (NSMutableArray *)selectedAssetURLs {
    if(!_selectedAssetURLs){
        _selectedAssetURLs=[NSMutableArray array];
    }
    return _selectedAssetURLs;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    _curTweet = [[Tweet alloc] init];
    //添加分割线
    [self createView];
    [self.view addSubview:self.tableView];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(refresh:) name:@"RefreshImage_gj" object:nil];
    //没有任何数据 有巡检督办带入的图片 添加到附件。
    if(self.selectedAssetURLs.count==0){
        //巡检带入附件添加到数组
        if(self.inspectFileArray&&self.inspectFileArray.count>0){
            for (NSString *str in self.inspectFileArray) {
                [self.selectedAssetURLs addObject:str];
            }
        }
    }
    
    // 刷新附件
    [self refresh:nil];
}

// 添加通知
- (void)viewWillAppear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveImage) name:@"addJGDB_ClickSave" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"addJGDB_ClickSave" object:nil];
}

//添加分割线
- (void)createView {
    UIView *line_1=[[UIView alloc]initWithFrame:CGRectMake(0, LINE_Y, DEF_SCREEN_WIDTH, 1)];
    line_1.backgroundColor=[UIColor colorWithRed:0.91 green:0.91 blue:0.91 alpha:1.00];
    [self.view addSubview:line_1];
    
    UIView *line_2=[[UIView alloc]initWithFrame:CGRectMake(DEF_SCREEN_WIDTH/2-0.5, LINE_Y, 1, DEF_SCREEN_HEIGHT-10)];
    line_2.backgroundColor=[UIColor colorWithRed:0.91 green:0.91 blue:0.91 alpha:1.00];
    [self.view addSubview:line_2];
    
    //添加文字
    UILabel *lab_1=[[UILabel alloc]initWithFrame:CGRectMake(DEF_SCREEN_WIDTH/8, LINE_Y/2, DEF_SCREEN_WIDTH/4, LINE_Y)];
    lab_1.text=@"整改前附件";
    lab_1.textAlignment=1;
    lab_1.backgroundColor=[UIColor whiteColor];
    lab_1.font=[UIFont systemFontOfSize:14.];
    [self.view addSubview:lab_1];
    
    UILabel *lab_2=[[UILabel alloc]initWithFrame:CGRectMake(DEF_SCREEN_WIDTH/8*5, LINE_Y/2, DEF_SCREEN_WIDTH/4, LINE_Y)];
    lab_2.text=@"整改后附件";
    lab_2.textAlignment=1;
    lab_2.backgroundColor=[UIColor whiteColor];
    lab_2.font=[UIFont systemFontOfSize:14.];
    [self.view addSubview:lab_2];
}

//刷新附件
- (void)refresh:(id)sender{
    if(self.selectedAssetURLs != nil){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            self.curTweet.selectedAssetURLs = self.selectedAssetURLs;
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        });
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return  [AttachmentPhotoCell cellHeightWithObj:_curTweet];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WEAKSELF
    AttachmentPhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1" forIndexPath:indexPath];
    cell.isEdit = YES;
    cell.curTweet = _curTweet;
    
    //巡检带入整改前附件
    if(self.isInspect){
        //不显示删除按钮
        cell.isDEL=YES;
        cell.fileArray=[NSMutableArray arrayWithArray:self.inspectFileArray];
    }
    
    cell.addPicturesBlock = ^(){
        [weakSelf showActionForPhoto];
    };
    
    cell.deleteTweetImageBlockUrl= ^(TweetImage *toDelete,NSString *deUrl){
        //移除图片
        [weakSelf.curTweet deleteATweetImage:toDelete];
        //移除数组
        [weakSelf.selectedAssetURLs removeObject:deUrl];
        
        [weakSelf refresh:nil];
    };
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    return cell;
}

/*
 *  此方法让cell横线置顶
 */
-(void)viewDidLayoutSubviews {
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}

- (void)saveImage {
    //流程记录ID
    NSString *recordId=self.processId;
    //删除以前的附件
    if(!recordId&&recordId.length<=0){
        recordId = [NSUUID UUID].UUIDString;
    }
    // 附件信息新增附件表
    NSArray *fileinfosArr = [self insertAttachment:recordId];
    NSString *fileinfosStr;
    if(fileinfosArr){
        fileinfosStr = [LSUtility toJSONData:fileinfosArr];
    }else{
        fileinfosStr = @"";
    }
    NSMutableDictionary *mDic = [NSMutableDictionary dictionary];
    [mDic setObject:recordId forKey:@"ID"];
    [mDic setObject:DEFISNUL(fileinfosStr) forKey:@"ARRAY"];
    NSNotification *noc = [NSNotification notificationWithName:@"chuanzhi" object:nil userInfo:mDic];
    [[NSNotificationCenter defaultCenter] postNotification:noc];
}

#pragma mark - 先新增附件表
- (NSArray *)insertAttachment:(NSString *)recordIds {
    NSArray *rFileArr;
    if (self.selectedAssetURLs.count>0){
        NSString *processType;
        if (self.addDuB) {
            processType = @"PROCESS_01";
        } else if (self.addGJ) {
            processType = @"PROCESS_02";
        }
        rFileArr = [LSUtility insertAttachmentFromArray:self.selectedAssetURLs andRecordId:recordIds andType:processType andRecifyState:@"0"];
    }
    return rFileArr;
}

#pragma mark UIActionSheet M
- (void)showActionForPhoto{
    [self.view endEditing:YES];
    //    @weakify(self);
    [[UIActionSheet bk_actionSheetCustomWithTitle:nil buttonTitles:@[@"拍照", @"从相册选择"] destructiveTitle:nil cancelTitle:@"取消" andDidDismissBlock:^(UIActionSheet *sheet, NSInteger index) {
        
        [self photoActionSheet:sheet DismissWithButtonIndex:index];
        
    }] showInView:self.view];
}

- (void)photoActionSheet:(UIActionSheet *)sheet DismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //拍照
        if (_curTweet.tweetImages.count >= 9) {//照片最多这么多
            kTipAlert(@"最多只可选择9张照片，已经选满了。先去掉一张照片再拍照呗～");
            return;
        }
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = NO; // 设置可编辑
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];//进入照相界面
    }else if (buttonIndex == 1){
        PictureViewController *picCtr=[[PictureViewController alloc]init];
        picCtr.flag=@"file";
        NSMutableArray *array = [self.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
        picCtr.selectedImages = [[NSMutableArray alloc] initWithArray:array];
        picCtr.selectedImageBlock = ^(NSMutableArray *array){
            self.selectedAssetURLs = [NSMutableArray arrayWithArray:array];
        };
        [self.navigationController pushViewController:picCtr animated:YES];
    }
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    self.curTweet.editImageView = [[EditImageView alloc]initWithImage:image];
    WEAKSELF
    self.curTweet.editImageView.completeBlock = ^(NSString *path) {
        //添加选择附件
        [weakSelf.curTweet addASelectedAssetURL:path];
        [weakSelf.selectedAssetURLs addObject:path];
        //刷新指定行
        [weakSelf.tableView reloadData];
    };
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"RefreshImage_gj" object:nil];
}


@end

